package com.gimi.cloud.mmf.gateway.service.impl;


import java.util.Map;

import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.gimi.cloud.mmf.common.utils.JsonUtil;
import com.gimi.cloud.mmf.common.utils.StringUtil;
import com.gimi.cloud.mmf.gateway.common.Exemption;
import com.gimi.cloud.mmf.gateway.config.redis.RedisServiceImpl;
import com.gimi.cloud.mmf.gateway.dao.ConfigDao;
import com.gimi.cloud.mmf.gateway.entity.Config;
import com.gimi.cloud.mmf.gateway.service.ExemptionService;

/**
 * Created by shazhiwei on 2017/10/26.
 */
@Service
public class ExemptionServiceImpl implements ExemptionService {
    private final ConfigDao configDao;
    private final RedisServiceImpl redisService;

    public ExemptionServiceImpl(ConfigDao configDao,RedisServiceImpl redisService){
        this.configDao = configDao;
        this.redisService = redisService;
    }
    @Override
    public Map<String, String> getExemptionMap() {
        Map<String, String> result = Exemption.apiMap;
        try{
            String redisData = redisService.get("ExemptionServiceName");
            if(!StringUtil.isBlank(redisData)){
                result = JsonUtil.jsonToMap(redisData);
            }else {
                Map<String, String> reload = reloadExemption();
                if(reload != null){
                    result = reload;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    private Map<String, String> reloadExemption(){
        Map<String, String> result = null;
        Config entity = new Config();
        entity.setNid("exemption_service_name");
        Example<Config> ex = Example.of(entity);
        configDao.findOne(ex);
        if(entity != null && entity.getId() != null){
            String mysqlData = entity.getValue();
            Map<String, String> dataMap = JsonUtil.jsonToMap(mysqlData);
            if(dataMap != null && dataMap.size() > 0){
                result = JsonUtil.jsonToMap(mysqlData);
                redisService.set("ExemptionServiceName",mysqlData);
            }
        }
        return result;
    }
}
